package com.learn.sc.springbootdemo.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.learn.sc.springbootdemo.pojo.RetDataBean;
import com.learn.sc.springbootdemo.pojo.Users;
import com.learn.sc.springbootdemo.service.LoginService;
import com.learn.sc.springbootdemo.tools.RedisService;

import com.learn.sc.springbootdemo.tools.enums.RetStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@RestController
@CrossOrigin
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    LoginService loginService;

    @Autowired
    RedisService redisService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping(value = "/learn/login", method = RequestMethod.POST)
    public RetDataBean loginUsers(@RequestBody @Validated Users users){
        RetDataBean retDataBean = new RetDataBean(RetStatus.SUCCESS_STATUS.getRetCode(),RetStatus.SUCCESS_STATUS.getRetMsg());
        try {
            String imageCode = users.getUserId();
            String verifyCode = null;
            if(redisService.hasKey("imageCode")){
                 verifyCode = redisService.get("imageCode").toString();
            }
            if (imageCode.equals(verifyCode)){
                retDataBean = loginService.loginValidateInfo(users,retDataBean);
            }else{
                retDataBean.setRetCode("-1");
                retDataBean.setRetMsg("验证码输入有误");
            }
        }catch (Exception e){
            logger.error("登录验证异常"+e.getMessage());
            retDataBean.setRetCode("-1");
            retDataBean.setRetMsg("登录验证异常，请稍后重试");
        }
        return retDataBean;
    }

    @RequestMapping(value = "/learn/register", method = RequestMethod.POST)
    public RetDataBean registerUsers(@RequestBody @Validated Users users){
        RetDataBean retDataBean = new RetDataBean("0");
        try {
            retDataBean = loginService.registerInfo(users, retDataBean);
        } catch (Exception e) {
            logger.error("注册异常:"+e.getMessage());
            retDataBean.setRetCode("-1");
            retDataBean.setRetMsg("注册失败，请稍后重试");
        }
        return retDataBean;
    }

    @GetMapping("/learn/createImageCode")
    public void createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 生成文字验证码
        String text = defaultKaptcha.createText();
        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        // 这里我们使用redis缓存验证码的值，并设置过期时间为90秒
        redisService.set("imageCode",text);
        redisService.expire("imageCode",90);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }
}
